package com.sky.controller.admin;
import com.sky.constant.MessageConstant;
import com.sky.properties.UpYunOssProperties;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import com.upyun.RestManager;
import com.upyun.UpException;
import com.upyun.UpYunUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    @Resource
    private UpYunOssProperties upload;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传：{}",file);

        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀   dfdfdf.png
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;
            RestManager manager = new RestManager(upload.getUP_BUCKET_NAME(), upload.getUP_USER_NAME(), upload.getUP_PASSWORD());

            Map<String, String> params = new HashMap<>();
            // GMT格式时间
            params.put("Date", UpYunUtils.getGMTDate());
            params.put("Content-Length", file.getSize() + "");
            //上传路径
            String path = upload.getUP_FilePath()+"/"+objectName;
            // 上传图片
            Response result = manager.writeFile(path, file.getBytes(), params);
            if (result.isSuccessful()) {
                log.info(String.valueOf(result));
                // 访问链接
                String url = "https://img.linxin.cc" + path;
                return Result.success(url);
            } else {
                // 上传失败
                return Result.error(result.message());
            }
        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
        } catch (UpException e) {
            throw new RuntimeException(e);
        }

        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
